package com.gy.def.controller;

import com.gy.def.enums.ResultEnum;
import com.gy.def.exception.GySchoolException;
import com.gy.def.utils.GetRandomNum;
import com.gy.def.utils.ResultVoUtil;
import com.gy.def.viewobject.ResultVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

@Api(value = "upFileController", description = "上传文件模块")
@RestController
@RequestMapping("/upFile")
@Slf4j
public class UpFileController {

  @Value("${sys.imgPath}")
  private String imgPath;

  @Value("${sys.linuxImgPath}")
  private String linuxImgPath;

  @ApiOperation(value = "上传文件", notes = "上传文件")
  @ApiImplicitParams({
    @ApiImplicitParam(paramType = "query", name = "type", value = "上传类型(0:消息图片 1:账号头像)", required = true, dataType = "string"),
  })
  @ApiParam(name = "file", value = "图片文件", required = true)
  @PostMapping(value = "/upPicture", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResultVo upPicture(@RequestParam("file") MultipartFile file,
                            @RequestParam("type") Integer type) {

    if (file.isEmpty()) {
      throw new GySchoolException(ResultEnum.ErrorFileEmpty);
    }

    String os = System.getProperty("os.name");
    String realImgPath = imgPath;
    if (os.toLowerCase().startsWith("linux")) {
      realImgPath = linuxImgPath;
    }

    switch (type) {
      case 0://营业执照
        realImgPath += "BookSendMsgImg/";
        break;
      case 1://身份证
        realImgPath += "BookSendAccountImg/";
        break;
      default://其他文件
        realImgPath += "BookSendOtherFiles/";
        break;
    }

    //日期分类 新的一天创建一个新的文件夹
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String location = df.format(new Date()) + System.getProperty("file.separator");
    realImgPath += location;
    File targetFile = new File(realImgPath);
    if (!targetFile.exists()) {
      boolean makeResult = targetFile.mkdirs();
      if (!makeResult) {
        throw new GySchoolException(ResultEnum.ErrorDicCreateFail);
      }
    }

    String oldFileName = file.getOriginalFilename();

    assert oldFileName != null;
    String oldFileNameType = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);

    String fileName = new Date().getTime() + GetRandomNum.getCCode() + "." + oldFileNameType;
    String url;
    try {
      Files.copy(file.getInputStream(), Paths.get(realImgPath, fileName), StandardCopyOption.REPLACE_EXISTING);
      if (os.toLowerCase().startsWith("linux")) {
        realImgPath = realImgPath.replaceAll(linuxImgPath, "");
      } else {
        realImgPath = realImgPath.replaceAll(imgPath, "");
      }
      url = Paths.get(realImgPath, fileName).toString();
      return ResultVoUtil.success(url);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ResultVoUtil.error(ResultEnum.ErrorFileUpFail.getCode(), ResultEnum.ErrorFileUpFail.getMessage());
  }
}
